package xdu.lz.stage2_design_pattern.chapter2_single_pattern;

public class Singleton4 {


    private Singleton4(){

    }

    //利用java内存模型保证类初始化是安全的。
    //static只有在第一次getInstance时候 去加载，并且Java内存保证了线程安全性以及内存一致性。
    //既保证了线程安全又保证了延迟加载
    private static class InstanceHolder{

        private static final Singleton4 instance = new Singleton4();
    }

    public static Singleton4 getInstance(){
        return InstanceHolder.instance;
    }

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                System.out.println(Singleton4.getInstance());
            }).start();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis() - time);
    }
}
